package org.tea.inventory.admin.annotation.support;

import lombok.extern.slf4j.Slf4j;

import org.tea.inventory.admin.annotation.AuthorizedUser;
import org.tea.inventory.base.contants.Constants;
import org.tea.inventory.cache.constans.CacheConstants;
import org.tea.inventory.cache.utils.RedisUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Slf4j
public class AuthorizedUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(String.class) && parameter.hasParameterAnnotation(AuthorizedUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        String authorization = request.getHeader(Constants.AUTHORIZATION);
        if (authorization == null || authorization.isEmpty()) {
            return null;
        }
        String key= CacheConstants.redisKey +authorization+":";
        String loginId = String.valueOf(RedisUtil.get(key));
        log.info("登录key{},value{}",key,loginId);
        return loginId;
    }
}
